/*
 * @Author: c
 * @Date: 2024-01-08 17:35:47
 * @LastEditTime: 2024-01-19 18:33:41
 * @LastEditors: c
 * @Description: 
 * @FilePath: \music-web-backend\src\core\music\picture\picture.service.ts
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { generateFileId } from 'src/common/utils';
import { FileDescDto } from 'src/core/system/minio/dto/create-file.dto';
import { FileInfo } from 'src/core/system/minio/entities/file_info.entity';
import { MinioClientService } from 'src/core/system/minio/minio.service';
import { DataSource, Repository } from 'typeorm';
import { CreatePictureDto } from './dto/create-picture.dto';
import { UpdatePictureDto } from './dto/update-picture.dto';
import { Picture } from './entities';

@Injectable()
export class PictureService {

  constructor(
    @InjectRepository(Picture) private pictureRepository: Repository<Picture>,
    private readonly minioClientService: MinioClientService,
    private dataSource: DataSource
  ) { }

  create(createPictureDto: CreatePictureDto) {
    return 'This action adds a new picture';
  }

  findAll() {
    return `This action returns all picture`;
  }

  findOne(id: number) {
    return `This action returns a #${id} picture`;
  }

  update(id: number, updatePictureDto: UpdatePictureDto) {
    return `This action updates a #${id} picture`;
  }

  remove(id: number) {
    return `This action removes a #${id} picture`;
  }


  /**
   * 图片-软删除
   * @param fileid 
   */
  async deleteSolftPic(fileid: string) {


    const queryRunner = this.dataSource.createQueryRunner()
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      await queryRunner.manager.createQueryBuilder().softDelete().from(Picture)
        .where("file_id = :fileid", { fileid })
      await queryRunner.manager.createQueryBuilder().softDelete().from(FileInfo)
        .where("id = :fileid", { fileid })

      await queryRunner.commitTransaction()
    } catch (error) {
      await queryRunner.rollbackTransaction()
    } finally {
      await queryRunner.release()
    }


  }


  /**
 * 图片-硬删除
 * @param id 图片id
 */
  async deletePicById(id: string) {
    const data = await this.pictureRepository.findOne({ where: { id: id }, relations: ['fileInfo'] });
    await this.pictureRepository.remove(data);

  }

  /**
   * 图片-硬删除
   * @param fileid 文件id
   * @param objectName minio的文件名称
   */
  async deletePic(req, file: FileDescDto) {

    const fileId = generateFileId(req.user.username, file.uid, file.name)
    

    const fileData = await this.minioClientService.findOne(fileId);
    
    if (fileData && fileData.deleted) {

      const queryRunner = this.dataSource.createQueryRunner()
      await queryRunner.connect();
      await queryRunner.startTransaction();

      try {
        await this.minioClientService.removeObject('public', fileData.name)
        await queryRunner.manager.createQueryBuilder().delete().from(Picture)
          .where("file_id = :fileid", { fileId })
        await queryRunner.manager.createQueryBuilder().delete().from(FileInfo)
          .where("id = :fileId", { fileId })

        await queryRunner.commitTransaction()
      } catch (error) {
        await queryRunner.rollbackTransaction()
      } finally {
        await queryRunner.release()
      }


    }

  }
}